﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class SceneManager : MonoBehaviour {

	#region Singleton
	public static SceneManager _Instace = null;

	public static SceneManager Instance
	{
		get
		{
			if(!_Instace)
			{
				_Instace = FindObjectOfType<SceneManager>();
			}
			return _Instace;
		}
	}
	#endregion

	void Awake()
	{
		DontDestroyOnLoad(gameObject);
	}

	void Start()
	{
		Application.LoadLevel(1);
		SetCurrentScene(1);
	}

	public List<SceneID> loadedScenes = new List<SceneID>();
	public SceneID currentScene;
	public int sceneToSet = -1;

	void SetCurrentScene(int _id)
	{
		bool found = false;
		foreach(SceneID scene in loadedScenes)
		{
			if(scene.ID == _id)
			{
				currentScene = scene;
				sceneToSet = -1;
				found = true;
				break;
			}
		}
		if(!found)
		{
			sceneToSet = _id;
			return;
		}

		//Find scenes to unload
		List<SceneID> unload = new List<SceneID>();
		foreach(SceneID scene in loadedScenes)
		{
			bool keep = false;
			for(int i=0; i<currentScene.adjacent.Length; ++i)
			{
				if(scene.ID == currentScene.adjacent[i])
				{
					keep = true;
					break;
				}
			}
			if(!keep)
			{
				unload.Add(scene);
			}
		}

		//Don't unload current scene
		unload.Remove(currentScene);

		//Unload
		foreach(SceneID scene in unload)
		{
			loadedScenes.Remove(scene);
			Destroy(scene.gameObject);
		}

		//Load new scenes
		for(int i=0; i<currentScene.adjacent.Length; ++i)
		{
			found = false;
			foreach(SceneID scene in loadedScenes)
			{
				if(currentScene.adjacent[i] == scene.ID)
				{
					found = true;
					break;
				}
			}
			if(!found)
			{
				Application.LoadLevelAdditive(currentScene.adjacent[i]);
			}
		}
	}

	public void SceneLoaded(SceneID _scene)
	{
		if(!loadedScenes.Contains(_scene))
		{
			loadedScenes.Add(_scene);
		}
	}

	void Update()
	{
		if(sceneToSet != -1)
		{
			SetCurrentScene(sceneToSet);
		}
	}
}
